package com.zoweunion.mechanic.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class PhoneCode {
	public static void main(String[] args) throws Exception{
		getAuth();
		String url = "https://cloud.zoweunion.com/API/Contact/SMS";
		String interface_account = "YSZH";
		String unify_account = "f5dd714c40f39db1533efbeb5b25af0e59e81492";
		String appSecret = getPostAuthorization(url, interface_account, unify_account);
		List<BasicNameValuePair> content = new ArrayList<BasicNameValuePair>();
		content.add(new BasicNameValuePair("phonenum", "18552076533"));
		content.add(new BasicNameValuePair("content", "测试"));
		//System.out.println(doPost(url,appSecret,content));
	}

	public static String getPostAuthorization(String url, String interface_account, String unify_account) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
		String time = df.format(new Date());
		String str = "TOS username=" + "\"" + interface_account + "\"" + ",uri=" + "\"" + url + "\"" + ",response="
				+ "\"" + MD5.md5(time + ":" + "POST" + ":" + url + ":" + unify_account) + "\"";
		return str;
	}

	public static String doPost(String url, String interface_account, String unify_account, String phonenum, String content1) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		String result = "";
		String appSecret = getPostAuthorization(url, interface_account, unify_account);
		List<BasicNameValuePair> content = new ArrayList<BasicNameValuePair>();
		content.add(new BasicNameValuePair("phonenum", phonenum));
		content.add(new BasicNameValuePair("content", content1));
		try {
			// 通过址默认配置创建一个httpClient实例
			httpClient = HttpClients.createDefault();
			// 创建httpGet远程连接实例
			HttpPost httpPost = new HttpPost(url);

			// 设置请求头信息，鉴权
			httpPost.setHeader("Authorization", appSecret);
			httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
			// 设置配置请求参数
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
					.setConnectionRequestTimeout(35000)// 请求超时时间
					.setSocketTimeout(60000)// 数据读取超时时间
					.build();
			// 为httpGet实例设置配置
			httpPost.setConfig(requestConfig);

			// 包装请求体
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.addAll(content);
			HttpEntity request = new UrlEncodedFormEntity(params, "UTF-8");
			// 发送请求
			httpPost.setEntity(request);

			// 执行get请求得到返回对象
			response = httpClient.execute(httpPost);
			// 通过返回对象获取返回数据
			HttpEntity entity = response.getEntity();
			// 通过EntityUtils中的toString方法将结果转换为字符串
			result = EntityUtils.toString(entity, "utf-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != response) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}


	public static String getAuth() throws Exception{
		// 官网获取的 API Key 更新为你注册的
		String clientId = "9EVsI9kdgtc0KEt2PfRPNwGD";
		// 官网获取的 Secret Key 更新为你注册的
		String clientSecret = "YpAKYqKuF0kuVlcvtLQcpQ7kncLl6Zen";
		return getAuth(clientId, clientSecret);
	}

	/**
	 * 获取API访问token
	 * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
	 *
	 * @param ak - 百度云官网获取的 API Key
	 * @param sk - 百度云官网获取的 Securet Key
	 * @return assess_token 示例：
	 * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
	 */
	public static String getAuth(String ak, String sk) throws Exception {
		// 获取token地址
		String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
		String getAccessTokenUrl = authHost
				// 1. grant_type为固定参数
				+ "grant_type=client_credentials"
				// 2. 官网获取的 API Key
				+ "&client_id=" + ak
				// 3. 官网获取的 Secret Key
				+ "&client_secret=" + sk;
		try {
			URL realUrl = new URL(getAccessTokenUrl);

			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.err.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			/**
			 * 返回结果示例
			 */
			JSONObject jsonObject = new JSONObject(result);
			String access_token = jsonObject.getString("access_token");
			return access_token;
		} catch (Exception e) {
			System.err.printf("获取token失败！");
			e.printStackTrace(System.err);
		}
		return null;
	}
}

